package com.edu.util;

import java.sql.*;

//数据库工具类，有获取连接、释放资源方法
public class DBUtil {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/nep?characterEncoding=utf-8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "Kd060122#";
    private static final ThreadLocal<Connection> TL = new ThreadLocal<>();

    private static Connection createConnection() throws SQLException {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    public static Connection getConnection() throws SQLException {
        Connection conn = TL.get();
        if(conn==null){
            conn = createConnection();
            TL.set(conn);
        }
        return conn;
    }

    public static void close(Connection conn, Statement st, ResultSet rs){
        try {
            if(rs!=null){
                rs.close();
            }
            if(st!=null){
                st.close();
            }
            if(conn!=null){
                conn.close();
                conn = TL.get();
                if(conn!=null){
                    conn.close();
                    TL.remove();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
